package com.xf.lastmall.service.impl;


import com.xf.lastmall.order.api.dto.WXBillCheckResultDto;
import com.xf.lastmall.moudle.entity.OrderMainEntity;
import com.xf.lastmall.moudle.entity.OrderTagsEntity;
import com.xf.lastmall.repository.*;
import com.xf.lastmall.service.OrderManageService;
import com.xf.lastmall.service.OrderTagsService;
import com.xf.lastmall.util.IdGenUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangzhaoqian5 on 2018/6/5.
 */
@Slf4j
@Service
public class OrderManageServiceImpl implements OrderManageService {
    @Resource
    private OrderDetailRepository orderDetailRepository;
    @Resource
    private OrderMainRepository orderMainRepository;
    @Resource
    private OrderRefundRepository orderRefundRepository;

    @Resource
    private OrderLogisticRepository orderLogisticRepository;

    @Resource
    private OrderInvoiceRepository orderInvoiceRepository;

    @Resource
    private OrderTagsService orderTagsService;


    @Override
    public void saveOrderInfo(OrderMainEntity orderMainEntity) {
        orderMainRepository.save(orderMainEntity);
        orderDetailRepository.saveAll(orderMainEntity.getOrderDetailEntityList());
        if (orderMainEntity.getInvoiceEntity() != null) {
            orderInvoiceRepository.save(orderMainEntity.getInvoiceEntity());
        }
        if (!CollectionUtils.isEmpty(orderMainEntity.getLogisticsEntities())) {
            orderMainEntity.getLogisticsEntities().forEach(p -> orderLogisticRepository.save(p));
        }
        //插入售卖标签
        final List<OrderTagsEntity> entities = new ArrayList<>();
        orderMainEntity.getOrderDetailEntityList().stream().filter(p -> !CollectionUtils.isEmpty(p.getTags())).forEach(p -> {
            for (String tagId : p.getTags()) {
                entities.add(OrderTagsEntity.builder().id(IdGenUtil.getNextId()).orderNo(orderMainEntity.getOrderNo()).commodityNo(p.getCommodityNo()).tagId(tagId).userId(orderMainEntity.getMemberId()).mobile(orderMainEntity.getMemberMobile()).build());
            }
        });
        if (!CollectionUtils.isEmpty(entities)) {
            orderTagsService.insert(entities);
        }
    }

    @Override
    public int updateOrderForCancelRefund(String refundNo, String orderSubNo, int numb) {
        int i = orderDetailRepository.revertRefundNum(orderSubNo, numb);
        if (i == 1) {
            orderRefundRepository.deleteByRefundNo(refundNo);
        }
        return i;
    }


    @Override
    public OrderMainEntity findOrderMainDetail(String orderId, String orderNo) {
        return orderMainRepository.findByIdAndOrderNo(orderId, orderNo);
    }


    @Override
    public List<WXBillCheckResultDto> findExtraOrderDetail(List<String> orderList) {
        return null;
    }


}


